package com.example.coreshopapp.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.coreshopapp.MainActivity;
import com.example.coreshopapp.R;
import com.example.coreshopapp.adapter.OrderAdapter;
import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.base.BaseActivity;
import com.example.coreshopapp.bean.GoodsData;
import com.example.coreshopapp.bean.MemberData;
import com.example.coreshopapp.bean.MemberGoodsReq;
import com.example.coreshopapp.databinding.ActivityOrderPayBinding;
import com.example.coreshopapp.net.BaseApplication;
import com.example.coreshopapp.task.GetMemberGoodsTask;
import com.example.coreshopapp.task.MemberTask;
import com.example.coreshopapp.utils.LoadingUtils;
import com.example.coreshopapp.utils.OrderingUtils;
import com.example.coreshopapp.utils.PhoneRegexUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import bean.OrderBean;
import bean.OrderItemBean;
import dao.DaoSession;
import dao.OrderBeanDao;
import dao.OrderItemBeanDao;

@SuppressLint("SetTextI18n")
public class OrderPayActivity extends BaseActivity {
    private ActivityOrderPayBinding binding;
    private DaoSession daoSession;
    private OrderBeanDao orderBeanDao;
    private OrderItemBeanDao orderItemBeanDao;
    private OrderAdapter orderAdapter;
    private OrderBean orderInfo;
    private List<OrderItemBean> orderItemList;
    private AlertDialog alertDialog;
    private MemberData memberInfo;
    private MemberTask memberTask;
    private GetMemberGoodsTask getMemberGoodsTask;
    private List<GoodsData> memberGoods;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_pay);
        hideTopBar();
        binding = ActivityOrderPayBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
        getGreenDao();
        ViewClick();
    }

    @SuppressLint("HandlerLeak")
    private Handler searchHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            alertDialog.dismiss();
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    List<MemberData> memberList = JSON.parseArray(msg.obj.toString(), MemberData.class);
                    if (memberList.size() > 0) {
                        memberInfo = memberList.get(0);
                        Constants.AppConstVars.MemberInfo = memberInfo;
                        setting();
                        // 提交数据后端拿会员价格
                        getMemberGoods();
                    } else {
                        Toast.makeText(OrderPayActivity.this, "当前号码未注册会员", Toast.LENGTH_LONG).show();
                    }
                    break;
                case 9901:
                    Toast.makeText(OrderPayActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(OrderPayActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(OrderPayActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler goodsHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    Log.d("memberGoodsList: ", msg.obj.toString());
                    memberGoods = JSON.parseArray(msg.obj.toString(), GoodsData.class);
                    changeGoodsPrice();
                    break;
                case 9901:
                    Toast.makeText(OrderPayActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(OrderPayActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(OrderPayActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };

    private void initView() {
        daoSession = BaseApplication.getInstance().getDaoSession(OrderPayActivity.this);
        orderBeanDao = daoSession.getOrderBeanDao();
        orderItemBeanDao = daoSession.getOrderItemBeanDao();

        orderAdapter = new OrderAdapter(orderItemList);
        binding.orderItem.setAdapter(orderAdapter);

        memberTask = new MemberTask();
        getMemberGoodsTask = new GetMemberGoodsTask();
    }

    private void getGreenDao() {
        getOrderDao();
//        getOrderItemDao();
    }

    private void ViewClick() {
        binding.goPayOrder.setOnClickListener(view -> {
            Bundle bundle = new Bundle();
            bundle.putString("orderId", orderInfo.getOrderId());
            gotoActivity(PayActivity.class, bundle);
        });

        // 交接班
        binding.btnSetclass.setOnClickListener(view -> {
            gotoActivityFinish(MainActivity.class);
        });
        // 登录会员
        binding.tvMemberLogin.setOnClickListener(view -> {
            // 创建弹窗
            EditText editText = new EditText(getActivity());
            editText.setHint("请输入会员号");
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
//            editText.setText(e.getNums() +""); 如果已有登录过得会员放在这里
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, // 宽度填满父容器
                    LinearLayout.LayoutParams.WRAP_CONTENT  // 高度根据内容自适应
            );
//        editText.setInputType(InputType.TYPE_CLASS_NUMBER |
//                InputType.TYPE_NUMBER_FLAG_DECIMAL | 带小数
//                InputType.TYPE_NUMBER_FLAG_SIGNED); 带负数
            editText.setLayoutParams(params);
            // 设置边距
            LinearLayout layout = new LinearLayout(getActivity());
            layout.setPadding(50, 30, 50, 30);
            layout.addView(editText);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("请输入会员号")
                    .setView(layout)
                    .setPositiveButton("确定", (dialog, which) -> {
                        String input = editText.getText().toString().trim();
                        // 处理输入内容
                        if (!PhoneRegexUtils.isValidPhone(input)) {
                            showtoast(this,"请输入正确的手机号");
                             return;
                        }
                        LoadingUtils.showProgressDialog(OrderPayActivity.this, "温馨提示", "加载中，请稍后");
                        HashMap<String, String> key = new HashMap<>();
                        memberTask.setSearchOutHandler(searchHandler);
                        key.put("key", input);
                        memberTask.execute(key);
                    })
                    .setNegativeButton("取消", null);
            alertDialog = builder.create();
            alertDialog.show();
        });
        binding.btnBack.setOnClickListener(view -> {
            gotoActivityFinish(ClassifyActivity.class);
        });
    }

    private void getOrderDao() {
        List<OrderBean> list = orderBeanDao.queryBuilder().where(
                OrderBeanDao.Properties.Isdel.notEq(true)
        ).list();
        if (list.size() > 0) {
            orderInfo = list.get(0);
        } else {
            orderInfo = null;
        }
        getOrderItemDao(orderInfo.getOrderId());
    }

    private void getOrderItemDao(String orderId) {
        orderItemList = orderItemBeanDao.queryBuilder().where(
                OrderItemBeanDao.Properties.OrderId.eq(orderId)
        ).list();
        orderAdapter.updateOrderAdapter(orderItemList);
        total();
    }

    ;

    public void total() {
        binding.orderQuantity.setText("共计" + orderInfo.getSumQuantity() + "件商品");
        binding.foodPriceTv.setText("￥" + orderInfo.getGoodsAmount());
        binding.tvTotalQty.setText(orderInfo.getSumQuantity() + "");
        binding.tvTotalAcamt.setText(orderInfo.getGoodsAmount() + "");
        binding.tvTotalAmt.setText(orderInfo.getGoodsAmount() + "");
        setting();
    }

    private void setting() {
        MemberData info = Constants.AppConstVars.MemberInfo;
        binding.tvMemberpoint.setText(info == null ? "0.00" : info.getPoint() + ""); // 判断会员是否登录，会员积分
        binding.tvMemberamount.setText(info == null ? "0.00" : info.getBalance() + ""); // 判断会员是否登录，会员余额
        binding.tvMemberLogin.setText(info == null ? "请登录会员" : info.getNickName() + "--" + info.getGradeName()); // 判断会员是否登录，会员账号
    }

    private void getMemberGoods() {
        LoadingUtils.showProgressDialog(OrderPayActivity.this, "温馨提示", "加载中，请稍后");
        ArrayList<Integer> objects = new ArrayList<>();
        for (OrderItemBean item : orderItemList) {
            objects.add(item.getProductId());
        }
        MemberGoodsReq memberGoodsReq = new MemberGoodsReq(objects, Constants.AppConstVars.MemberInfo.id);
        getMemberGoodsTask.setOutHandler(goodsHandler);
        getMemberGoodsTask.execute(memberGoodsReq);
    }

    private void changeGoodsPrice() {
        // 修改全部价格，并且修改总的哪一项价格
        orderItemList.forEach(item -> {
            memberGoods.forEach(ele -> {
                if (item.getProductId() == ele.getId()) {
                    OrderItemBean load = orderItemBeanDao.load(item.getId());
                    load.setPromotionPrice(ele.getPromotionPrice() > 0 ? ele.getPromotionPrice() : ele.getPrice());
                    load.setAmount(OrderingUtils.toFixed(load.getNums() * (ele.getPromotionPrice() > 0 ? ele.getPromotionPrice() : ele.getPrice())));
                    orderItemBeanDao.update(load);
                }
            });
        });
        orderItemList = orderItemBeanDao.queryBuilder().where(
                OrderItemBeanDao.Properties.OrderId.eq(orderInfo.getOrderId())
        ).list();
        orderAdapter.updateOrderAdapter(orderItemList);
        calculateTotalPrice();
    }

    private BigDecimal quantityMaster = new BigDecimal(0);
    private BigDecimal sumAmount = new BigDecimal(0);

    private void calculateTotalPrice() {
        quantityMaster = quantityMaster.subtract(quantityMaster);
        sumAmount = sumAmount.subtract(sumAmount);
        orderItemList.forEach(item -> {
            quantityMaster = quantityMaster.add(BigDecimal.valueOf(item.getNums()));
            sumAmount = sumAmount.add(BigDecimal.valueOf(item.getAmount()));
        });
        int num = OrderingUtils.calculateNum(quantityMaster);
        OrderBean load = orderBeanDao.load(orderInfo.getOrderId());
        load.setGoodsAmount(OrderingUtils.toFixedTwo(sumAmount));
        load.setSumQuantity(num);
        orderBeanDao.update(load);
        total();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
    }
}